package com.kang.auth.controller;

import com.kang.auth.service.AuthService;
import com.kang.common.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AuthController {

	private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

	@Autowired
	private AuthService authService;

	@GetMapping("/auth")
	public R authUser(@RequestParam String username, @RequestParam String password) {
		try {
			// 参数校验
			if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
				logger.warn("Authentication failed: Missing username or password.");
				return R.error("Username or password cannot be empty");
			}

			// 生成一个token
			String token = authService.auth(username, password);

			if (token == null) {
				logger.warn("Authentication failed: Invalid username or password.");
				return R.error("Invalid username or password");
			}

			logger.info("Authentication successful for user: {}", username);

			// 将这个token返回给前端
			return R.ok().put("token", token);
		} catch (Exception e) {
			logger.error("Error during authentication", e);
			return R.error("An unexpected error occurred. Please try again later.");
		}
	}
}
